package de.fhl.subWaehlerVerzeichnis;

/**
 * Ueberschrift:  OnlineWahl
 * Copyright:     Copyright (c) 2010 
 * Organisation:  FH Luebeck - Virtuelle FH
 */

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.hibernate.HibernateException;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;

import de.fhl.entity.Waehler;
import de.fhl.util.HibernateUtil;

/**
 * Die Klasse ImportWaehlerListe importiert eine Wählerliste in die Datenbank<br>
 *  
 * @author Achim Krumrein (krumreia@stud.fh-luebeck.de)
 * @author Thomas Weber (webertho@googlemail.de)
 * @version 1.0
 */
public class ImportWaehlerliste {

	public static void main(String[] args) throws Exception {

		try {
			int id = 0;
			File file = new File("doc/Waehlerliste_komplett.txt");
			FileReader fr = new FileReader(file);
			BufferedReader br = new BufferedReader(fr);

			StringBuffer sb = new StringBuffer();
			String eachLine = br.readLine();

			while (eachLine != null) {

				String[] sa = eachLine.split(";");
				++id;

				ImportWaehlerliste iwl = new ImportWaehlerliste();
				iwl.saveWaehlerliste(id, sa[1], sa[2], sa[4].trim(), sa[3], sa[5]);
				
				sb.append(eachLine);
				sb.append("\n");
				eachLine = br.readLine();
				Thread.sleep(100);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	public void saveWaehlerliste(int id, String name, String ausweisNr, String wahlkreis, String loginId, String status) {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {

			transaction = session.beginTransaction();
			Waehler waehler = new Waehler();
			waehler.setId(id);
			waehler.setName(name);
			waehler.setAusweisNr(ausweisNr);
			waehler.setWahlkreis(Integer.parseInt(wahlkreis));
			waehler.setLoginId(loginId);
			waehler.setStatus(status);
			
			session.persist(waehler);
			transaction.commit();

		} catch (HibernateException e) {

			transaction.rollback();
			e.printStackTrace();

		} finally {
			session.close();
		}
	}

}
